Partition array for maximum sum¶
Time: O(NxK); Space: O(K); medium
Given an integer array A, you partition the array into (contiguous) subarrays of length at most K. After partitioning, each subarray has their values changed to become the maximum value of that subarray.
Return the largest sum of the given array after partitioning.
Example 1:
Input: A = [1,15,7,9,2,5,10], K = 3
Output: 84
Explanation:
A becomes [15,15,15,9,10,10,10]
Constraints:
1 <= K <= len(A) <= 500
0 <= A[i] <= 10^6
Hints:
Think dynamic programming: dp[i] will be the answer for array A[0], …, A[i-1].
For j = 1 .. k that keeps everything in bounds, dp[i] is the maximum of dp[i-j] + max(A[i-1], …, A[i-j]) * j.
1. Dynamic programming [O(NxK), O(K)]¶
[1]:
class Solution1(object):
"""
Time: O(N*K)
Space: O(K)
"""
def maxSumAfterPartitioning(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
W = K + 1
dp = [0]*W
for i in range(len(A)):
curr_max = 0
# dp[i % W] = 0; # no need in this problem
for k in range(1, min(K, i+1) + 1):
curr_max = max(curr_max, A[i-k+1])
dp[i % W] = max(dp[i % W], (dp[(i-k) % W] if i >= k else 0) + curr_max*k)
return dp[(len(A)-1) % W]
[2]:
s = Solution1()
A = [1,15,7,9,2,5,10]
K = 3
assert s.maxSumAfterPartitioning(A, K) == 84